package com.mima.minaserver.service;


import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.jgroups.demos.wb.SendDialog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mima.minaserver.entity.Camera;
import com.mima.minaserver.entity.HeartBeatEntity;
import com.mima.minaserver.entity.HeartBeatMongoEntity;
import com.mima.minaserver.entity.MyUUID;
import com.mima.minaserver.repository.CameraRepository;
import com.mima.minaserver.repository.HeardBeatRepository;
import com.mima.minaserver.repository.HeartBeatMongoRepository;
import com.mima.minaserver.repository.IotServerMessageManagerRepository;
import com.mima.minaserver.server.IOTServerHandler;
import com.mima.minaserver.server.IOTServerHandlerThread;
import com.mima.minaserver.utils.ParameterUtils;

@Service
public class IotServerMessage {
	private static Logger logger = LoggerFactory.getLogger(IotServerMessage.class);
	@Autowired
	HeardBeatRepository heardBeatRepository;
	
	@Autowired
	HeartBeatMongoRepository heartBeatMongoRepository;
	
	@Autowired
	private IotServerMessageManagerRepository iotServerMessageManagerRepository;
	
	@Autowired
	private CameraRepository cameraRepository;
	
	@Autowired
	private AliCloudMessage aliCloudMessage;
	
	@Autowired
	ParameterUtils parameterUtils;
	
	public void sendDeviceOnOFFMessage(IoSession session,int on_or_off,int channel) {

		
		byte[] OPNMDA_CLSMDA = null;
		if(0 == on_or_off) OPNMDA_CLSMDA = "OPNMDA".getBytes();
		else if(1 == on_or_off) OPNMDA_CLSMDA = "CLSMDA".getBytes();
		else return;
		byte[] IP = getbyteIPHexString(parameterUtils.getAli_streaming_ip());
		
		byte[] PORT = new byte[2];
		PORT[0] = (byte)((parameterUtils.getAli_streaming_port() >>> 8) & 0xff );  
		PORT[1] = (byte)((parameterUtils.getAli_streaming_port() >>> 0) & 0xff );  

		byte[] CHANNAL = String.valueOf(channel).getBytes();
		byte[] bytes = new byte[OPNMDA_CLSMDA.length+IP.length+PORT.length+CHANNAL.length];

		System.arraycopy(OPNMDA_CLSMDA, 0, bytes, 0, OPNMDA_CLSMDA.length);
		System.arraycopy(IP, 0, bytes, OPNMDA_CLSMDA.length, IP.length);
		System.arraycopy(PORT, 0, bytes, OPNMDA_CLSMDA.length+IP.length, PORT.length);
		System.arraycopy(CHANNAL, 0, bytes, OPNMDA_CLSMDA.length+IP.length+PORT.length, CHANNAL.length);
		
		session.write(IoBuffer.wrap(bytes));
		logger.info("Send -{OPNMDA_CLSMDA="+OPNMDA_CLSMDA+",IP="+IP+",PORT="+PORT+",CHANNAL="+CHANNAL+",time="+new Date()+"}");
	}
	// 更新用户名及口令包
	public void sendUnameAndPWDMessage(IoSession session,String username,String pwd) {

		byte[] chgusr = "CHGUSR".getBytes();
		byte[] usernamePWD = (username+","+pwd).getBytes();
		
		byte[] bytes = new byte[usernamePWD.length+chgusr.length];
		
		System.arraycopy(chgusr, 0, bytes, 0, chgusr.length);
		System.arraycopy(usernamePWD, 0, bytes, chgusr.length, usernamePWD.length);
		session.write(IoBuffer.wrap(bytes));
		logger.info("Send CHGUSR-{uuid=xxxxxxxxx,username="+username+",pwd="+pwd+",time="+new Date()+"}");
	}
	
	// 更新秘钥
	public void sendSecretKeyMessage(IoSession session,String uuidString,int keyId,String key) {
		byte[] chgkey = "CHGKEY".getBytes();
		byte[] uuid = uuidString.getBytes();
		byte[] keyid = IOTServerHandler.intToBytes(keyId);
		byte[] keys = key.getBytes();
		
		byte[] bytes = new byte[chgkey.length+uuid.length+keyid.length+keys.length];
		
		System.arraycopy(chgkey, 0, bytes, 0, 6);
		System.arraycopy(uuid, 0, bytes, 6, 32);
		System.arraycopy(keyid, 0, bytes, 38, 1);
		System.arraycopy(keys, 0, bytes, 39, keys.length);
		session.write(IoBuffer.wrap(bytes));
		logger.info("Send CHGKEY-{uuid="+uuid+",keyId="+keyId+",key="+key+",time="+new Date()+"}");
	}
	
	//更新ip地址
	public byte[] getbyteIPHexString(String str) {
		byte[] result = new byte[4];
		String ips[] = str.split("\\.");
		for (int i=0;i<ips.length;i++) {
			String hexString = Integer.toHexString(new Integer(ips[i]));
			if (hexString.length() != 2) hexString = "0" + hexString;
			byte ipByte = Integer.valueOf(hexString,16).byteValue();
			result[i] = ipByte;
		}
		return result;
	}

	
	public void updateHeadBeat (String uuid,String username,String password,Date heartTime,Integer key_id) {
		logger.info("Receive---{uuid="+uuid+",username="+username+",password="+password+",heartTime="+heartTime+",key_id="+key_id+",time="+new Date()+"}");
		heardBeatRepository.updateHeadBeat(uuid,username, password,heartTime,key_id);
		
	}
	public void insertHeadBeat (String uuid,String username,String password,Date heartTime,Integer key_id) {
		logger.info("Receive---{uuid="+uuid+",username="+username+",password="+password+",heartTime="+heartTime+",key_id="+key_id+",time="+new Date()+"}");
		heardBeatRepository.save(new HeartBeatEntity(uuid,username,password,heartTime,key_id));
		
	}
	
	public HeartBeatEntity fetchHeadBeat (String uuid) {
		logger.info("Receive---{uuid="+uuid+"}");
		return heardBeatRepository.fetchHeadBeat(uuid);
		
	}


	public void insertHeadBeatToMongo (String uuid,String username,String password,Date heartpTime,Integer key_id) {
		logger.info("Receive---{uuid="+uuid+",username="+username+",password="+password+",heartpTime="+heartpTime+",key_id="+key_id+",time="+new Date()+"}");
		heartBeatMongoRepository.save(new HeartBeatMongoEntity(uuid,username,password,heartpTime,key_id));
	}
	
	
	public Date getDate(String time) {
		Long dec_num = Long.parseLong(time, 16) * 1000;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(dec_num);
		return calendar.getTime();
	}
	
	public MyUUID findUUIDByUUID(String UUID) {
		logger.info("Receive---{UUID="+UUID+",time"+new Date()+"}");
		return iotServerMessageManagerRepository.findUUIDByUUID(UUID);
	}
	public Camera findDeviceByUUID(String UUID) {
		logger.info("Receive---{UUID="+UUID+",time"+new Date()+"}");
		return cameraRepository.findDeviceByUUID(UUID);
	}
	public void updateStatusByUUID(int status,String uuid) {
		logger.info("Receive---{status="+status+",uuid="+uuid+",time"+new Date()+"}");
		cameraRepository.updateStatusByUUID(status, uuid);
	}
	public void PushLoginInfo(String uuid,int keyId,String secretkey, String url) throws ClientProtocolException, IOException {
		logger.info("Receive---{uuid="+uuid+",keyId="+keyId+"secretkey"+secretkey+",time"+new Date()+"}");
		aliCloudMessage.PushLoginInfo(uuid,keyId,secretkey, url);
	}
	public void updateCameraRtmpurl(String rtmpurlString,String Uuid) {
		logger.info("Receive---{rtmpurlString="+rtmpurlString+",Uuid="+Uuid+",time"+new Date()+"}");
		cameraRepository.updateCameraRtmpurl(rtmpurlString,Uuid);
	}
	
}
